package cn.itcast.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //得到请求路径
        String uri = req.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);
        System.out.println(method);
        //通过请求路径反射获取方法
        try {
            Method methodName = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //调用方法
            methodName.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
    public void writeJson(HttpServletResponse response,Object object) throws IOException {
        //设置json数据格式
        response.setContentType("application/json;charset=utf-8");
        //转换对象
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getWriter(),object);

    }
}
